package Factory.request;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.util.ArrayList;
import java.util.Map;

public class RequestParams extends DefaultRequestParams {

    private ArrayList<String> fields;

    private Object params;

    private HttpHeaders headers;

    private String content_type;

    public ByteBuf getParams() {
        ByteBuf buf = Unpooled.buffer();
        if (params != null) {
            buf = Unpooled.copiedBuffer(this.params.toString(), CharsetUtil.UTF_8);;
        }
        return buf;
    }

    public RequestParams setParams(Object params) {
        this.params = params;
        return this;
    }

    public HttpHeaders getHeaders() {
        return headers;
    }

    public RequestParams setHeaders(HttpHeaders headers) {
        this.headers = headers;
        return this;
    }

    public RequestParams setHeaders(Map<String, Object> map) {
        map.keySet().forEach(item -> {
            if (!this.fields.contains(item)) {
                this.headers.add(item, (CharSequence) map.get(item));
            }
        });
        return this;
    }

    public RequestParams setContentType(String content_type) {
        this.content_type = content_type;
        this.headers.remove(HttpHeaderNames.CONTENT_TYPE);
        this.headers.add(HttpHeaderNames.CONTENT_TYPE, content_type);
        return this;
    }

    public String getContent_type() {
        return this.content_type;
    }

    public RequestParams (HttpVersion httpVersion, HttpMethod httpMethod, URI uri) {
        this.setHttpMethod(httpMethod);
        this.setHttpVersion(httpVersion);
        this.setUri(uri);
        this.headers = new DefaultHttpHeaders();

        this.fields= new ArrayList<>();
        fields.add("method");
        fields.add("params");
        fields.add("uri");
        fields.add("Content-Length");
        fields.add("content-length");
    }

}
